<?php
/**
 * Created by PhpStorm.
 * User: FDG296
 * Date: 2017/8/2
 * Time: 16:42
 * 
 * 修改时间：2018/1/19
 * 修改人：lizenan
 * 修改功能：【后台需求】关键词维护改进
 * 任务ID：430
 */
namespace common\models;

use common\helps\getActivityMessage;
use Yii;
use yii\db\ActiveRecord;

class GoodsList extends ActiveRecord{

	public $categoryAggregate	=[];		//查询条件的分类集合
	public $brandAggregate		=[];		//查询条件的品牌集合

	const USE_FLG_YES			=1;
	const USE_FLG_NO			=0;

	public static function tableName(){
        return '{{%goods_list}}';
    }

    //根据main_goods_id获取主商品列表
    public function getMainGoodsList($main_goods_id){
        if(!empty($main_goods_id)){
            $where = [self::tableName().'.use_flg'=>1,self::tableName().'.main_goods_id'=>$main_goods_id];
            $main_goods_list = $this::find()
				->where($where)
				->joinWith('markImgInfo')
				->asArray()
				->all();
        }

        if(empty($main_goods_list)){
            $main_goods_list = array();
        }
        //add by huangzhao 20180116 456 【商城需求】商城所有界面商品价格的小数部分都不显示 start
        else{
            foreach($main_goods_list as &$res){
                $res['market_price'] = number_format($res['market_price'],0);
                $res['sale_price'] = number_format($res['sale_price'],0);

				//add by FDG367 495 【商城需求】商品图片上增加促销打标 2018-02-02 start
				//print_r($res);exit;
				$res['activity_message']	= GoodsList::getGoodsListActivity($res['main_goods_id']);
				//add by FDG367 495 【商城需求】商品图片上增加促销打标 2018-02-02 end
            }
        }
        //add by huangzhao 20180116 456 【商城需求】商城所有界面商品价格的小数部分都不显示 end
        return $main_goods_list;
    }

    //根据$goods_id获取主商品列表以及相应品牌信息 TODO 待修改
    public function getMainGoodsListByGoodsId($main_goods_id){
        /*$main_goods_list = array();*/
        if(!empty($main_goods_id)){
            $where = ['l.use_flg'=>self::USE_FLG_YES,'l.main_goods_id'=>$main_goods_id];
            $main_goods_list = $this::find()->alias('l')->where($where)->
            leftJoin('j_goods_brand as s','l.brand_id = s.id')->select('l.*,s.country_icon,s.country_name,s.brand_story,s.logo')->asArray()->one();
        }

        if(empty($main_goods_list)){
            $main_goods_list = array();
        }
        /*else{
            $command = (new \yii\db\Query())->select(['min(sale_price) as min_price', 'max(sale_price) as max_price'])
                ->from('j_goods_sale')->where(['main_goods_id' => $main_goods_id])->createCommand();
            $post = $command->queryOne();
            $main_goods_list['min_price'] = $post['min_price'];
            $main_goods_list['max_price'] = $post['max_price'];
        }*/
        return $main_goods_list;
    }

    //获取品类列表
    public function getTagList($brand_id,$category_id = ''){
        $where[] = 'and';
        $where[] = ['brand_id'=>$brand_id];
        if(!empty($category_id)){
            $where[] = ['category_step1'=>$category_id];
        }
        //$where = ['use_flg'=>1,'brand_id'=>$brand_id,'category_step1'=>$category_id];
        $result = $this::find()->where($where)->select('tag_id,tag_name')->distinct()->asArray()->all();
        return $result;
    }

    //获取品牌列表
    public function getBrandList($tag_id,$category_id = ''){
        $where[] = 'and';
        $where[] = ['tag_id'=>$tag_id];
        if(!empty($category_id)){
            $where[] = ['category_step1'=>$category_id];
        }
        //$where = ['use_flg'=>1,'tag_id'=>$tag_id,'category_step1'=>$category_id];
        $result = $this::find()->where($where)->select('brand_id,brand_name')->distinct()->asArray()->all();
        return $result;
    }

    //获取品类列表
    public function getTagListBySearch($search){
        $goods_where[] = 'and';
        $goods_where[] = ['use_flg'=>1];
//         $goods_where[] = 'FIND_IN_SET(:category_to_find, keyword_name)';
        $goods_where[] = ['like','keyword_name',$search];
        $result = $this::find()->where($goods_where)->select('tag_id,tag_name')->distinct()->asArray()->all();
        return $result;
    }

    //获取品牌列表
    public function getBrandListBySearch($search){
        $goods_where[] = 'and';
        $goods_where[] = ['use_flg'=>1];
//         $goods_where[] = 'FIND_IN_SET(:category_to_find, keyword_name)';
        $goods_where[] = ['like','keyword_name',$search];
        $result = $this::find()->where($goods_where)->select('brand_id,brand_name')->distinct()->asArray()->all();
        return $result;
    }

	/**
	 * @param 赋值筛选条件
	 * @param string $cateId
	 * @param string $cate_child_id
	 * @param string $tag_id
	 * @param string $brand_id
	 * @param string $keyword
	 * @param string $main_goods_ids主商品id数组 ['d12121','2112121']
	 */
	public function getCategoryBrand($cateId='',$cate_child_id='',$tag_id='',$brand_id='',$keyword = '',&$goods_count = 0,$main_goods_ids=[]){
		$goodWhere = $this->getGoodsFitter($cateId,$cate_child_id,$tag_id,$brand_id,$keyword,$main_goods_ids);
		//获取满足条件的商品ID
		$goodIdAggregate	=self::find()
			->select(['goods_id','category_step2','brand_id'])
			->where($goodWhere)
			->asArray()
			->all();
            /* ->createCommand()
             ->getRawSql();*/

        $goods_count = empty($goodIdAggregate) ? 0 : count($goodIdAggregate);

		if(!$goodIdAggregate){
			return [];
		}

		$this->categoryAggregate	= array_unique(array_column($goodIdAggregate,'category_step2'));
		$this->brandAggregate		= array_unique(array_column($goodIdAggregate,'brand_id'));

		if($this->categoryAggregate){
			$this->categoryAggregate= GoodsCategory::find()
				->where(['in','id',$this->categoryAggregate])
				->andWhere(['use_flg'=>GoodsCategory::USE_FLG_YES])
				->asArray()
				->all();
		}

		if($this->brandAggregate){
			$this->brandAggregate= GoodsBrand::find()
				->where(['in','id',$this->brandAggregate])
				->andWhere(['use_flg'=>GoodsCategory::USE_FLG_YES])
				->asArray()
				->all();
		}
	}

	/**
	 * @param 商品的筛选条件 mod  by FDG367 2018/04/09 571 【商城需求】商城导航目录修改。（包含Mobile导航、Mobile首页导航、PC导航） start 新增主商品id
	 * @param string $cateId
	 * @param string $cate_child_id
	 * @param string $tag_id
	 * @param string $brand_id
	 * @param string $main_goods_ids 主商品ID集合  ['123','456']
	 * @return array
	 */
	public function getGoodsFitter($cateId='',$cate_child_id='',$tag_id='',$brand_id='',$keyword = '',$main_goods_ids=[]){
		$goodWhere		= array();
        $goodWhere[] = 'and';
        $goodWhere[] = [self::tableName().'.use_flg'=>1];
		//一级分类
		if($cateId){
			$goodWhere[] = [self::tableName().'.category_step1'=>$cateId];
		}

		//二级分类
		if($cate_child_id){
			$goodWhere[] = [self::tableName().'.category_step2'=>$cate_child_id];
		}

		//品类
		if($tag_id){
			$goodWhere[] = [self::tableName().'.tag_id'=>$tag_id];
		}

		//品牌
		if($brand_id){
			$goodWhere[] = [self::tableName().'.brand_id'=>$brand_id];
		}
		if(0<count($main_goods_ids)){
			$goodWhere[] = ['in','main_goods_id',$main_goods_ids];
		}

//         //搜索
//         if(!empty($keyword)){
//             $goodWhere[] = ['like','keyword_name',$keyword];
//         }
        //搜索
        if(!empty($keyword)){
            $name = self::tableName().'.keyword_name';
            $name_list = self::tableName().'.keyword_list';	//组合关键字列表
            $name_val = $keyword;
            if (is_array($keyword) && count($keyword) > 0){
                $name = array_keys($keyword)[0];
                $name_val = array_values($keyword)[0];
            }
            //mod by lizenan 20180119 【后台需求】关键词维护改进   430  start
            $goodWhere[] = ["like","CONCAT(IFNULL($name,''),IFNULL($name_list,''))",$name_val];
            //$goodWhere[] = ["like",$name,$name_val];
            //mod by lizenan 20180119 【后台需求】关键词维护改进   430  end
        }
		return $goodWhere;
	}


	//add by FDG367 495 【商城需求】商品图片上增加促销打标 2018-02-02 start
	/**
	 * @return \yii\db\ActiveQuery获取打标扩展信息
	 * @param 关联对应的商品打标信息
	 */
	public function getMarkImgInfo(){
		return $this->hasOne(GoodsMarkingImg::className(), ['id'=>'marking_img_id'])->andOnCondition([GoodsMarkingImg::tableName().'.use_flg'=>GoodsMarkingImg::STATUS_ENABLE]);
	}


	/**
	 * @param $mainGoodsId	根据主商品ID获取对应的促销信息
	 * @param $mainGoodsId 主商品id
	 * @param $isall true:主商品下的所有促销商品的集合；false:只是主商品的促销信息
	 * @return array
	 */
	public static function getGoodsListActivity($mainGoodsId,$isall=true){

		//搜索当前商品对应的促销活动   start
		if($isall){
			$sale_model		= new GoodsSale();

			//获取当前商品sku
			$sku_list 		= $sale_model->getSkuList($mainGoodsId,'','');

			//获取当前商品的大类
			$genre_type 	= $sale_model->getGenreTypeList($mainGoodsId,'','');
		//add by FDG367 495 【商城需求】心愿单界面，只显示主商品的促销标识 start
		}else{
			//获取主商品的基本信息
			$mainInfo		= self::getOneInfo($mainGoodsId);
			$sku_list		= [$mainInfo['sku']];
			$genre_type		= !empty($mainInfo['genre_type'])?[$mainInfo['genre_type']]:[];

		}
		//add by FDG367 495 【商城需求】心愿单界面，只显示主商品的促销标识 end

		//获取对应的信息
		$activity_model = new getActivityMessage();
		$cx_list = json_decode($activity_model->getActivityMessageData($sku_list,count($genre_type) > 0 ? $genre_type : ''),true);

		if($cx_list['code'] != 200){
			return [];
		}

		return $cx_list['data'];
		//获取商品促销扩展
	}
	//add by FDG367 495 【商城需求】商品图片上增加促销打标 2018-02-02 start

	public static function getOneInfo($mainGoodsId){
		return self::find()->where(['use_flg'=>self::USE_FLG_YES,'main_goods_id'=>$mainGoodsId])->one();
	}

	/**
	 * @return \yii\db\ActiveQuery获取打标扩展信息
	 */
	public function getBrandInfo(){
		return $this->hasOne(GoodsBrand::className(),['id'=>'brand_id'])->select([
			GoodsBrand::tableName().'.id',
		]);
	}
}